var fs = require("fs"),
	formidable = require("formidable"),
	util = require("util"),
	router = require("./router"),
	path = require('path'),
	url = require ("url"),
	qs = require ("querystring"),
	mime = require( "mime" );
	require("./dbase/db")

function htmlShow(response, request) {
	console.log("Request handler for '*.htm' file was called. ");
  var fileHtm = path.basename(request.url);  
  if (fileHtm == '')
  	fileHtm = '/start.html';

	response.writeHead(200, {"Content-Type":"text/html"});
	fs.readFile("./view/" + fileHtm, "utf8", function (err, data) {
				if (err) throw err;
				response.write(data);
				response.end();
			 }
	);
}

function css(response, request) {
	console.log("Request handler '*.css' was called.");
	var fileCss = path.basename(request.url);  
	response.writeHead(200, {"Content-Type":"text/css"});
	fs.readFile("./css/" + fileCss, "utf8", function (err, data) {
				if (err) throw err;
				response.write(data);
				response.end();
			 }
	);
}

function upload ( response, request ) {
    console.log( "Request for 'upload' is called." );
    
    var form = new formidable.IncomingForm();
    console.log( "Preparing upload" );
    form.parse( request, function( error, fields, files ) {
        console.log( "Completed Parsing" );
        if( error ){
            response.writeHead( 500, { "Content-Type" : "text/plain" } );
            response.end( "CRAP! " + error + "\n" );
            return;
        }
	      dbase.create(fields.username, fields.password);
	      dbase.find(fields.username);
			  var testpng = path.resolve("./tmp");
			  	  testpng = path.join(testpng ,  files.upload.name); 
			
		    var is = fs.createReadStream(files.upload.path);
		    var os = fs.createWriteStream(testpng);
		    is.pipe(os);
		    is.on('end',function() {
		      fs.unlinkSync(files.upload.path);
		    });	    
		    response.writeHead( 200, { "Content-Type" : "text/html" } );
		    response.write( "received image" );
		    response.write( "<img src='/show?i=" + files.upload.name + "' alt='' />" ); 
		    response.write( 'username <span class="auth"> ' + fields.username +
		                    '  password = ' + fields.password + "<br/>"  );
		    response.end();
    });
}


function show( response, request ) {  
    console.log( "Request handler 'show' was called. " );
    var image = qs.parse( url.parse( request.url ).query ).i; 
    var testpng = path.resolve("./tmp");
		 	  testpng = path.join(testpng ,  image); 
    
    if( !image ) { 
        response.writeHead( 500, { "Content-Type" : "text/plain" } );
        response.end( " No Image in QueryString ");
        return;
    }
    fs.readFile( testpng, "binary", function( error, file ) { 
        var type = ""; // Mime-Type value
        if (error) {
        	response.writeHead( 500, { "Content-Type" : "text/plain" } );
        	response.end( error + "\n" );
        	return;
        } 
        type = mime.lookup( file ); 
        response.writeHead( 200, { "Content-Type" : type } ); 
        response.end( file, "binary" );      
      });
}

//exports.start = start;
exports.upload = upload;
exports.show = show;
exports.css = css;
exports.htmlShow = htmlShow;